const cheerio = require("cheerio")
const http = require("http")

const baseUrl = "http://www.bimiacg4.net"

const detailUrl = 'http://www.bimiacg4.net/bangumi/bi/2818/'

const playerUrl = 'http://www.bimiacg4.net/bangumi/909/play/3/1/'


// search("异世界", 1).then( data => 
//     console.log(data)
// )

// detail(detailUrl).then(data => {
//     console.log(JSON.stringify(data))
// })


// source(detailUrl).then( data => {
//     console.log(JSON.stringify(data))
// })


// related(detailUrl).then( data => {
//     console.log(data)
// })


// table(1).then(data => {
//     console.log(data)
// })


// timeline().then(data => {
//     console.log(data)
// })

// ranking().then(data => {
//     console.log(data)
// })

// playUrl(playerUrl).then(data => {
//     console.log(data)
// })


async function getHome() {
    let html = await getHtml(baseUrl)
    let $ = cheerio.load(html)

    let fl = $('div.area-main.fl')
    return fl.map((i, e) => {
        let $e = cheerio.load(e)
        let body = {}
    
        let label = $e('div h2 b').text()
        
        let items = $e('li').map((i, ee) => {
            $ee = cheerio.load(ee)
            let item = {
                title: $ee('a').attr('title'),
                url: baseUrl + $ee('a').attr('href'),
                coverUrl: $ee('a img').attr('src'),
                status: $ee('div p').attr('title')
            }
            return item
        }).toArray()
    
        body.label = label
        body.items = items

        return body
    
    }).toArray()
}

async function search(keyword, page) {
    const url = baseUrl + "/vod/search/wd/"+ keyword + "/page/" + page
    let html = await getHtml(url)
    let $ = cheerio.load(html)

    let li = $('div.v_tb ul li.item')
    
    return li.map((i, e) => {
        let $e = cheerio.load(e)
        let item = {}
        
        item.title = $e('a').attr('title')
        item.url = baseUrl + $e('a').attr('href')
        item.cover = $e('a img').attr('src')
        item.status = $e('div p').attr('title')
        return item
    }).toArray()
    
}


async function detail(url) {
    let html = await getHtml(url)
    let $ = cheerio.load(html)
    let row = $('div.row')[0]

    $ = cheerio.load(row)
    let li = $('ul li')

    return {
        title: $('img').attr('alt'),
        cover: $('img').attr('src'),
        extra: li.map((i, e) => {
            return $(e).text()
        }).toArray()
    }
    
}


async function source(url) {
    let html = await getHtml(url)
    let $ = cheerio.load(html)
    let tabs = $('div.play_source_tab a').map((i, e) => {
        let $e = cheerio.load(e)
        return $e.text()
    })
    let data = $('ul.player_list').map((i, e) => {
        let $e = cheerio.load(e)
        let source = {}
        source.sourceName = tabs[i]
        source.episodes = $e('li a').map((i, e) => {
            let episode = {}
            episode.title = $(e).text()
            episode.url = baseUrl + $(e).attr('href')
            return episode
        }).toArray()
        return source
    }).toArray()
    return data
}


async function playUrl(url) {
    const regex = /\{"flag":"(.+?)".*?"url":"(.+?)".*?"from":"(.+?)"/
    const fmlist = ['pic', 'danmakk']
    const iframe = baseUrl + '/static/danmu/%s.php?url=%s'
    const playUrlReg = /var url = '(.*?)'/

    let html = await getHtml(url)

    let match = html.match(regex)

    
    let id = match[2]
    let fm = match[3]
    let st = ''
    
    if(fmlist.indexOf(fm) >= 0) {
        st = fmlist[0]
    } else if(fm == 'renrenmi') {
        st = 'rrm'
    } else {
        st = 'play'
    }

    let iframeUrl = baseUrl + '/static/danmu/'+st+'.php?url=' + id
    let iframeHtml = await getHtml(iframeUrl)

    
    let playUrl = iframeHtml.match(playUrlReg)[1]
    
    if(playUrl.startsWith('http') == true) {
        return playUrl
    } else if(playUrl.length == 0) {
        return ''
    }
    
    return baseUrl + '/static/danmu/' + playUrl
    
}


async function related(url) {
    let html = await getHtml(url)
    let $ = cheerio.load(html)
    return $('div.love-det ul.drama-module li.item').map((_, e) => {
        let $e = cheerio.load(e)
        let item = {}
        item.title = $e('a').attr('title')
        item.url = baseUrl + $e('a').attr('href')
        item.cover = $e('a img').attr('src')
        item.status = $e('div p span').text()
        item.views = $e('div p em').text()
        
        return item
    }).toArray()

}


async function table(index) {
    const types = 'riman guoman fanzu juchang dianshiju move'.split(' ')
    let url = baseUrl + '/type/' + types[index] + '/'
    
    let html = await getHtml(url)
    let $ = cheerio.load(html)
    
    return $('ul.selcet_list li').map((_, e) => {
        let $e = cheerio.load(e)
        let tab = {}
        tab.name = $e('span').text()
        tab.items = $e('p span a').text()

        return tab
    }).toArray()
}



async function timeline() {
    let html = await getHtml(baseUrl)
    let $ = cheerio.load(html)
    
    let data = $('ul.tab-cont__wrap li').map((i, e) => {
        let $e = cheerio.load(e)
        return $e('ul li').map((i, ee) => {
            let $ee = cheerio.load(ee)

            let item = {}
            item.title = $ee('a:eq(1)').attr('title')
            item.url = baseUrl + $ee('a:eq(1)').attr('href')
            item.cover = $ee('a:eq(0) div img').attr('src')
            item.status = $ee('span:eq(0)').text()
            return item
        }).toArray()
    }).toArray()
    return data
}

async function ranking() {
    let html = await getHtml(baseUrl + '/label/top/')
    let $ = cheerio.load(html)
    let data = $('div.top-r div').map((_, e) => {
        let $e = cheerio.load(e)
        
        let rank = {}
        rank.title = $e('div:eq(0) span a').attr('title')
        rank.items = $e('ul:eq(0) li h3 a').map((_, ee) => {
            let item = {}
            item.title = $(ee).attr('title')
            item.url = baseUrl + $(ee).attr('href')
            
            return item
        }).toArray()
        return rank
        
    }).toArray()

    return data
}

async function getHtml(url) {
    let html = await new Promise((resovle, reject)=> {
        let req = http.request(url, (res) => {
            let truncks = []
            res.on('data', trunck => truncks.push(trunck))
            res.on('end', () => {
                const buff = Buffer.concat(truncks)
                const html = buff.toString("utf-8")
                resovle(html)
            })
            res.on('error', (e) => reject(e))
        })
        req.end()
    }) 
    return html
}

module.exports.getHome = getHome
module.exports.search = search
module.exports.detail = detail
module.exports.source = source
module.exports.playUrl = playUrl
module.exports.related = related
module.exports.table = table
module.exports.timeline = timeline
module.exports.ranking = ranking

